package com.wangijun.yuan.web.api;

import cloud.tianai.captcha.application.ImageCaptchaApplication;
import cloud.tianai.captcha.application.vo.CaptchaResponse;
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
import cloud.tianai.captcha.common.constant.CaptchaTypeConstant;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.wangijun.yuan.web.base.CommonResult;
import com.wangijun.yuan.core.model.em.OperateTypeEnum;
import com.wangijun.yuan.web.service.OperateInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;

@Tag(name = "1-全局通用接口")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/global")
public class GlobalController {
    private final FileStorageService fileStorageService;//注入实列
    private final OperateInfoService operateInfoService;


    @Operation(summary = "是否登录", description = "返回是否登录，true为登录，false为未登陆")
    @GetMapping("/is-login")
    CommonResult<Boolean> isLogin() {
        return CommonResult.data(StpUtil.isLogin());
    }


    record UserIdParam(
            @Schema(description = "用户ID")
            Long userId) {
    }

    @Operation(summary = "关注用户", description = "关注用户")
    @PostMapping("/follow-user")
    @Transactional
    CommonResult<Boolean> followUser(@RequestBody UserIdParam param) {
        if (param.userId == null) {
            CommonResult.error("用户Id不可为空");
        }
        long loginIdAsLong = StpUtil.getLoginIdAsLong();
        if (loginIdAsLong == param.userId) {
            CommonResult.error("自己不要关注自己喔~");
        }
        return CommonResult.data(operateInfoService.operate(OperateTypeEnum.user_follow, param.userId));
    }


    record TagIdParam(
            @Schema(description = "标签ID")
            Long tagId) {
    }

    @Operation(summary = "关注标签", description = "关注标签")
    @PostMapping("/follow-tag")
    @Transactional
    CommonResult<Boolean> followTag(@RequestBody TagIdParam param) {
        if (param.tagId == null) {
            CommonResult.error("标签Id不可为空");
        }
        return CommonResult.data(operateInfoService.operate(OperateTypeEnum.tag_follow, param.tagId));
    }

    record TopicIdParam(
            @Schema(description = "标签ID")
            Long topicId) {
    }

    @Operation(summary = "关注话题", description = "关注话题")
    @PostMapping("/follow-topic")
    @Transactional
    CommonResult<Boolean> followTopic(@RequestBody TopicIdParam param) {
        if (param.topicId == null) {
            CommonResult.error("话题Id不可为空");
        }
        return CommonResult.data(operateInfoService.operate(OperateTypeEnum.topic_follow, param.topicId));
    }

    public record Base64ImageParam(@Schema(description = "base64格式图片") String data) {
    }

    @Operation(summary = "上传Base64格式图片", description = "上传Base64图片接口")
    @PostMapping("/upload-base64-img")
    public CommonResult<FileInfo> uploadBase64Image(@RequestBody Base64ImageParam param) {
        String[] split = param.data().split(",");
        FileInfo fileInfo = fileStorageService.of(Base64.decode(split[1]))
                .setOriginalFilename(IdWorker.getIdStr() + "."
                        + split[0].split(";")[0].split(":")[1].split("/")[1])
                .thumbnail()
                .upload();
        return CommonResult.data(fileInfo);
    }


    public record ImageFile(@Schema(description = "文件内容") MultipartFile file) {
    }

    @Operation(summary = "上传图片", description = "单独上传图片接口")
    @PostMapping("/upload-img")
    public CommonResult<FileInfo> uploadImage(ImageFile file) {
        FileInfo fileInfo = fileStorageService.of(file.file)
                .thumbnail()
                .upload();
        return CommonResult.data(fileInfo);
    }


    public record HrefParam(@Schema(description = "图片url") String href) {
    }

    @Operation(summary = "删除图片", description = "物理删除图片根据图片Url")
    @PostMapping("/del-img")
    public CommonResult<Boolean> delImage(@RequestBody @Validated HrefParam param) {
        try {
            fileStorageService.delete(param.href);
        } catch (Exception e) {
            log.error("图片地址:{}删除错误", param.href, e);
        }
        return CommonResult.ok();
    }


    private final ImageCaptchaApplication imageCaptchaApplication;

    @Operation(summary = "获取验证码", description = "根据type获取验证码类型")
    @PostMapping("/captcha")
    public CaptchaResponse<ImageCaptchaVO> genCaptcha(String type) {
        if (StringUtils.isBlank(type)) {
            type = CaptchaTypeConstant.SLIDER;
        }
        if ("RANDOM".equals(type)) {
            int i = ThreadLocalRandom.current().nextInt(0, 4);
            if (i == 0) {
                type = CaptchaTypeConstant.SLIDER;
            } else if (i == 1) {
                type = CaptchaTypeConstant.CONCAT;
            } else if (i == 2) {
                type = CaptchaTypeConstant.ROTATE;
            }else if (i == 3) {
                type = CaptchaTypeConstant.WORD_IMAGE_CLICK;
            }

        }
        return imageCaptchaApplication.generateCaptcha(type);
    }

    @Operation(summary = "验证码验证", description = "验证验证码是否成功")
    @PostMapping("/captcha-check")
    public ApiResponse<?> checkCaptcha(@RequestBody DataDto data) {
        ApiResponse<?> response = imageCaptchaApplication.matching(data.id(), data.data());
        if (response.isSuccess()) {
            return ApiResponse.ofSuccess(Collections.singletonMap("id", data.id()));
        }
        return response;
    }

    @Schema(description = "验证码验证信息")
    public record DataDto(@Schema(description = "验证ID") String id, ImageCaptchaTrack data) {
    }


}
